package org.kev.transit.worker;

import java.util.ArrayList;
import org.kev.transit.data.RouteType;
import org.kev.transit.data.Stop;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class RouteTypeUpdateWorker implements Runnable{
	private static final String TAG = "RouteTypeUpdateWorker";
	private Activity mParent;
	private ArrayList<RouteType> mList;
	public RouteTypeUpdateWorker(Activity parent, ArrayList <RouteType> list){
		mParent=parent;
		mList=list;
	}
	public void run(){
		int count = mList.size();
		String where =null;		
		Cursor cursor = null;
		
		for(int i=0;i<count;i++){
			RouteType data = mList.get(i);
			//uri.addId(Long.parseLong(s.id) );
			where = RouteType.ROUTE_TYPE_ID + "=? ";
									
			Log.d(TAG,"wheres="+where);
			String args[]={data.id};

			try{
				cursor = mParent.managedQuery(RouteType.CONTENT_URI, new String[] 
				     {RouteType.ROUTE_TYPE_ID},where,args,null);
				//update lookup table
				Log.d(TAG,"found in db #"+cursor.count());
				
				if(cursor.count()==0){
					insertData(data);
				}else{
					updateData(data);
				}
			}catch(Exception e){
				Log.e(TAG,"UNKNOWN error will be ignored",e);
			}finally{
				if(cursor!=null)
					cursor.close();
			}

		}		
		
	}
	/**
	 * insert data object into DB table
	 * @param data
	 * @return row URI
	 */
	private Uri insertData(RouteType data){
		Log.d(TAG,">>> insertStop"+mParent+data);
		if (mParent ==null || data==null){
			return null;
		}

		Log.d(TAG, "+++insertRouteType");
		Log.d(TAG, data.toXml() );
		ContentValues values = new ContentValues();
		values.put(RouteType.ROUTE_TYPE_ID, data.id);
		values.put(RouteType.TITLE, data.title);
		values.put(Stop.CREATE_DATE,new  Long(System.currentTimeMillis() ) );
		
		Uri curl = mParent.getContentResolver().insert(RouteType.CONTENT_URI,values);
		//done with lookup now work on timeTable
			Log.d(TAG,"<<< insertRouteType"+curl);

		return curl;
	}

	/**
	 * update date in DB with data object
	 * @param data
	 * @return row count
	 */
	private int updateData(RouteType data){
		if (mParent ==null|| data==null){
			return 0;
		}
		Log.d(TAG, "+++updateStop");
		Log.d(TAG, data.toXml() );
		ContentValues values = new ContentValues();
		values.put(RouteType.ROUTE_TYPE_ID, data.id);
		values.put(RouteType.TITLE, data.title);
		values.put(RouteType.CREATE_DATE,new  Long(System.currentTimeMillis() ) );
		String where = RouteType.ROUTE_TYPE_ID+"=? ";
		String[] args={data.id};

		int row = mParent.getContentResolver().update(RouteType.CONTENT_URI,values,where,args);
		Log.d(TAG,"row="+row );
		return row;
	}

}
